package com.ossjk.qlh.system.service.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.ossjk.core.util.CommonUtil;
import com.ossjk.qlh.system.entity.Department;
import com.ossjk.qlh.system.entity.Role;
import com.ossjk.qlh.system.mapper.DepartmentMapper;
import com.ossjk.qlh.system.service.IDepartmentService;

/**
 * <p>
 * 部门表 服务实现类
 * </p>
 *
 * @author chair
 * @since 2020-02-06
 */
@Service
public class DepartmentServiceImpl extends ServiceImpl<DepartmentMapper, Department> implements IDepartmentService {

	@Override
	public boolean removeChildrenById(Serializable id) {
		List<Department> departments = queryChildrenById(id);
		QueryWrapper<Department> queryWrapper = new QueryWrapper();
		List<Serializable> ids = new ArrayList<Serializable>();
		for (Department department : departments) {
			ids.add(department.getId());
		}
		return SqlHelper.retBool(baseMapper.deleteBatchIds(ids));
	}

	/**
	 * 查找所有子节点（包含自身）
	 * 
	 * @param id
	 * @return
	 */
	public List<Department> queryChildrenById(Serializable id) {
		List<Department> departments = null;
		Department department = baseMapper.selectById(id);
		if (!CommonUtil.isBlank(department)) {
			departments = new ArrayList();
			departments.add(department);
			queryChildrenByPid(department.getId(), departments);

		}
		return departments;
	}

	/**
	 * 查找所有子节点（不包含自身）
	 * 
	 * @param pid
	 * @param parent
	 * @return
	 */
	public List<Department> queryChildrenByPid(Serializable pid, List<Department> parent) {
		if (CommonUtil.isBlank(parent)) {
			parent = new ArrayList<Department>();
		}
		QueryWrapper<Department> queryWrapper = new QueryWrapper();
		List<Department> children = baseMapper.selectList(queryWrapper.eq("pid", pid));
		if (!CommonUtil.isBlank(children)) {
			parent.addAll(children);
			for (Department department : children) {
				queryChildrenByPid(department.getId(), parent);
			}
		}

		return parent;
	}

	@Override
	public List<String> listUserDidByUid(String uid) {
		return baseMapper.selectUserDidByUid(uid);
	}

}
